﻿using System;
using System.Web.Services;
using System.Web.UI.WebControls;
using Pharmacy.Web.UI;
using Pharmacy.Entities;
using Pharmacy.Data;
using Pharmacy.Settings.BusinessLayer;

public partial class Admin_ImportAdjustEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtil.RedirectAfterInsertUpdate(FormView1, "ImportAdjustEdit.aspx?{0}", GrnDataSource);
        FormUtil.RedirectAfterAddNew(FormView1, "ImportAdjustEdit.aspx");
        FormUtil.RedirectAfterCancel(FormView1, "ImportAdjust.aspx");
        FormUtil.SetDefaultMode(FormView1, "GrnId");
        if (!IsPostBack)
        {
            int count;
            TList<DrugDispo> all = DataRepository.DrugDispoProvider.GetPaged("", "DrugName", 0, Int32.MaxValue, out count);
            dataDrugId.DataSource = all;
            dataDrugId.DataBind();
        }
    }


    protected void FormView1_Load(object sender, EventArgs e)
    {
        DropDownList dataPreparedBy = (DropDownList)FormView1.Row.FindControl("dataPreparedBy");
        dataPreparedBy.SelectedValue = Request.Cookies["LoginUser"].Value;
        dataPreparedBy.Enabled = false;
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            TextBox dataGRNID = (TextBox)FormView1.Row.FindControl("dataGRNID");
            TextBox dataGRNDate = (TextBox)FormView1.Row.FindControl("dataGRNDate");
            //ServiceFacade.SettingsHelper.ImportAjustPrefix = "dj-";
            string Perfix = "I" + ServiceFacade.SettingsHelper.ImportAjustPrefix + DateTime.Now.ToString("yyMMdd");
            int Count = 0;
            TList<Grn> objGrn = DataRepository.GrnProvider.GetPaged("GrnId like '" + Perfix + "' + '%'", "GRNId desc", 0, 1, out Count);
            if (Count == 0)
                dataGRNID.Text = Perfix + "001";
            else
            {
                dataGRNID.Text = Perfix + String.Format("{0:000}", int.Parse(objGrn[0].GrnId.Substring(objGrn[0].GrnId.Length - 3)) + 1);
            }
            dataGRNDate.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            dataGRNDate.Enabled = false;
        }
        else
        {
            FormView1.FooterRow.FindControl("PreviewButton").Visible = true;

            string GrnId = Request.QueryString["GrnId"];
            Grn objGrn = DataRepository.GrnProvider.GetByGrnId(GrnId);
            if (objGrn.IsComplete != null && objGrn.IsComplete)
            {
                FormView1.FooterRow.FindControl("UpdateButton").Visible = false;
                FormView1.FooterRow.FindControl("CloseGrn").Visible = false;
            }
            else
            {
                FormView1.FooterRow.FindControl("CloseGrn").Visible = true;
                pn_PODetailsAdd.Visible = true;
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (btnSave.Text == "Add")
        {
            DateTime? expDate; DateTime dt;
            expDate = DateTime.TryParse(txtExpDate.Value, out dt) ? dt : (DateTime?)null;
            string batchLot = null;
            batchLot = (TxtBatchLot.Value == "null" || TxtBatchLot.Value.Trim() == "") ? null : TxtBatchLot.Value;
            GrnDetails objDetails = new GrnDetails();
            objDetails.DrugId = dataDrugId.SelectedValue;
            objDetails.Quantity = Int32.Parse(tbQuantity.Value);
            objDetails.Remark = tbRemark.Value;
            objDetails.BatchLot = batchLot;
            objDetails.ExpDate = expDate;
            DrugDispo objDrugDispo = DataRepository.DrugDispoProvider.GetByDrugId(objDetails.DrugId);
            objDetails.UnitPrice = objDrugDispo.CostPrice;
            TextBox dataGRN = (TextBox)FormView1.Row.FindControl("dataGrnId");
            objDetails.GrnId = dataGRN.Text;
            DataRepository.GrnDetailsProvider.Insert(objDetails);
            GridView1.DataBind();
            tbRemark.Value = "";
            tbQuantity.Value = "";
            dataDrugId.SelectedValue = "";
            dataDrugId.Focus();
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string urlParams = string.Format("GrnId={0}", GridView1.SelectedDataKey.Values[0]);
        Response.Redirect("ImportAdjustEdit.aspx?" + urlParams, true);
    }
    [WebMethod]
    public static void DeleteGrnDetail(string GrnDetailId)
    {
        DataRepository.GrnDetailsProvider.Delete(long.Parse(GrnDetailId));
    }

    protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "CloseGrn")
        {
            decimal Amount = 0;
            decimal totalAmount = 0;
            TextBox tbGrnID = (TextBox)FormView1.Row.FindControl("dataGrnID");
            //update stock
            Stock objStock;
            // int countstock = 0;
            TList<GrnDetails> listGrnDetail = DataRepository.GrnDetailsProvider.GetByGrnId(tbGrnID.Text);
            TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
            try
            {
                objTransactionManager.BeginTransaction();
                foreach (GrnDetails Itemdetail in listGrnDetail)
                {
                    objStock = DataRepository.StockProvider.GetByDrugIdExpDateBatchLot(objTransactionManager,Itemdetail.DrugId, Itemdetail.ExpDate, Itemdetail.BatchLot);
                    // if (countstock == 1
                    if (objStock != null)
                    {
                        objStock.Quantity += Itemdetail.Quantity;
                        objStock.UnitPrice = Itemdetail.UnitPrice;
                        DataRepository.StockProvider.Update(objTransactionManager,objStock);
                    }
                    else
                    {
                        objStock = new Stock();
                        objStock.DrugId = Itemdetail.DrugId;
                        objStock.Quantity = Itemdetail.Quantity;
                        objStock.UnitPrice = Itemdetail.UnitPrice;
                        objStock.ExpDate = Itemdetail.ExpDate;
                        objStock.BatchLot = Itemdetail.BatchLot;
                        DataRepository.StockProvider.Insert(objTransactionManager, objStock);
                    }
                    // tinh amount cho Grn_Amount
                    Amount = Itemdetail.Quantity * Itemdetail.UnitPrice;
                    totalAmount += Amount;
                }
                Grn objGrn = DataRepository.GrnProvider.GetByGrnId(objTransactionManager,tbGrnID.Text);
                if (objGrn != null)
                {
                    objGrn.IsComplete = true;
                    objGrn.Amount = totalAmount;
                    DataRepository.GrnProvider.Update(objTransactionManager,objGrn);
                }
                objTransactionManager.Commit();
            }
            catch (Exception)
            {
                objTransactionManager.Rollback();
                throw;
            }
            finally
            {
                //visible button
                GridView1.DataBind();
                FormView1.FooterRow.FindControl("CloseGrn").Visible = false;
                
            }
        }
        if (e.CommandName == "Preview")
        {
            string grnId = Request.QueryString["GrnId"].ToString();
            Response.Redirect("PreviewImportAdjust.aspx?GrnId=" + grnId);
        }
    }
}
